#! /usr/bin/python3.10
# coding=utf-8
# @Time：2025/8/6 19:36
# @Author：Shawn
# @introduction：
import base64

import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad


def get_device_triples_info(scada_sn: str = None, url: str = None):
    """
    AES-ECB模式解密函数

    参数:
    :param url:
    :param scada_sn: scada_sn
    :param url_bool: 布尔类型，True为测试环境的scada_sn，False为正式环境的scada_sn

    返回:
    解密后的明文字节串(bytes)

    异常:
    ValueError -- 如果输入格式无效或密钥长度不正确
    """
    # 测试环境的scada_sn
    try:
        url = url
        scada_sn_base64 = base64.b64encode(scada_sn.encode('utf-8')).decode('utf-8')
        print(scada_sn_base64)
        # 灰度获取三元组信息地址
        # if "https://huidu" in url:
        #     print(123)
        #     re_aes = requests.get(url=url + "/api/backstage/scada/getScadaKey", params={"key": scada_sn_base64})
        # else:
        #     re_aes = requests.get(url=url + "/api/backstage/scada/getScadaKey", params={"key": scada_sn_base64})
        re_aes = requests.get(url=url + "/api/backstage/scada/getScadaKey", params={"key": scada_sn_base64})

        if len(re_aes.text) == 0:
            print("当前环境没有找到scada_sn，请输入正确的scada_sn")
            return "当前环境没有找到scada_sn，请输入正确的scada_sn"
        elif re_aes.status_code != 200:
            print(f"地址访问不通，状态码：{str(re_aes.status_code)}，错误信息：{str(re_aes.text)}")
            return f"地址访问不通，状态码：{str(re_aes.status_code)}，错误信息：{str(re_aes.text)}"
        ciphertext = re_aes.text
        key = scada_sn[0:8] + scada_sn_base64[0:8]
        print(key)
    except Exception as e:
        return "获取scada_sn失败，失败原因：%s" % e

    # 处理密文输入
    if isinstance(ciphertext, str):
        # 尝试Base64解码
        try:
            ciphertext = base64.b64decode(ciphertext)
        except:
            # 尝试Hex解码
            try:
                ciphertext = bytes.fromhex(ciphertext)
            except:
                raise ValueError("密文格式无效(需Base64字符串、Hex字符串或bytes)")
    elif not isinstance(ciphertext, bytes):
        raise ValueError("密文类型无效(需str或bytes)")

    # 处理密钥输入
    if isinstance(key, str):
        # 检查是否为Hex格式
        if all(c in '0123456789abcdefABCDEF' for c in key) and len(key) in [32, 48, 64]:
            key = bytes.fromhex(key)
        else:
            key = key.encode('utf-8')
    elif not isinstance(key, bytes):
        raise ValueError("密钥类型无效(需str或bytes)")

    # 验证密钥长度
    if len(key) not in [16, 24, 32]:
        raise ValueError(f"无效密钥长度: {len(key)}字节(需16/24/32字节)")

    # 执行AES-ECB解密
    cipher = AES.new(key, AES.MODE_ECB)
    decrypted = cipher.decrypt(ciphertext)

    # 移除PKCS7填充
    return unpad(decrypted, AES.block_size).decode('utf-8')


if __name__ == '__main__':
    triples_info = get_device_triples_info("AF70020250829012", url="https://huidu-eurems.alphaess.com")
    print(triples_info)
